var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    danote:[],
    bannerList: [], //banner图
    token: '',
    curindex: 0,
    params:{
      page:1,
      size:10
    },

    getHongbao:false,
    list:[],
    pindaolist:[],

    pindaolist2:[],

    pindaolist3: [],
  
    icons: [],

    total3:0,
    hasphone: false,


    params2: {
      page: 1,
      size: 2
    }


    // openNew: false
  },


  changeModalCancel () {
    this.setData({
      openNew: false
    })
  },

  getXiaoxi () {

    var _this = this
    wx.requestSubscribeMessage({
      tmplIds: ["LVzud8OH3aHKpkwOBYKcL0pntVnKEGlTOHvUcIlzOXc"],
      success: (res) => {

        if (res['LVzud8OH3aHKpkwOBYKcL0pntVnKEGlTOHvUcIlzOXc'] === 'accept') {
          // wx.showToast({
          //   title: '授权成功',
          //   icon: 'none'
          // })
          // _this.setData({
          //   openNew: false
          // })
          _this.getDingyue(1)

        }else{
          _this.getDingyue(0)
          // _this.setData({
          //   openNew: false
          // })
        }

      },
      fail(err) {
        //失败
        console.error(err);
        // reject()
      }
    })
  },




  reloadHome () {


var _this = this
    setTimeout(function () {
      wx.pageScrollTo({
        scrollTop: 0,
        success: function () {
          var page = "params2.page"
          var size = "params2.size"
          _this.setData({
            [page]: 1,
            [size]: 2,
            pindaolist3: [],
          })

          _this.getChennianren(_this.data.params2)


          _this.getIcons()
          _this.getAllpindao()

          _this.getBanner()

          _this.getFivepingdao()

          _this.getWeichengnian()
        }
      })
    }, 1000)

    

  },


  goType(e) {

    console.log(e)

    var adultTypeName = e.currentTarget.dataset.adulttypename

    var imgurl = e.currentTarget.dataset.imgurl


    console.log(adultTypeName)

    if (adultTypeName != '必读' && adultTypeName!='全部') {
    wx.navigateTo({
      url: '/package/index/pages/newTypelist/newTypelist?adultTypeName=' + adultTypeName + '&imgurl=' + imgurl
    })
    } else if (adultTypeName == '全部') {
      wx.navigateTo({
        url: '/package/index/pages/bookSearch/bookSearch',
      })
    } else {
      wx.navigateTo({
        url: '/package/index/pages/biduBook/biduBook'
      })
    }
  },

  getActivity(e) {
    var key = e.currentTarget.dataset.key



    console.log(key)


    if (key == 1) {
      // wx.navigateTo({
      //   url: '/package/index/pages/newHuodong/newHuodong'
      // })

      wx.navigateTo({
        url: '/package/index/pages/newHuodongsan/newHuodongsan',
      })
    }
    if (key == 2) {
      wx.navigateTo({
        url: '/package/index/pages/newHuodonger/newHuodonger',
      })
      // if (wx.getStorageSync('token') == '') {
      //   this.setData({
      //     istokenPop: true
      //   })
      //   return
      // }
      // wx.navigateTo({
      //   url: '/package/my/pages/shareFriends/shareFriends'
      // })
    }

    if (key == 3) {
     wx.navigateTo({
        url: '/package/index/pages/newHuodong/newHuodong'
      })
    }
  },

  
  goTypelist() {
    wx.navigateTo({
      url: '/package/index/pages/typePage/typePage',
    })
  },

  getBanner() {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/publish/gets',
      data: {
        mainKey: 4
      },
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        // console.log(res.data.su)
        console.log(res.data.data.length)


        if (res.data.success) {

          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新

          var arr = res.data.data
          _this.setData({
            bannerList: arr
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  swiperChange(e) {
    // console.log(e.detail.current)

    this.setData({
      curindex: e.detail.current
    })
  },

  bookSearch () {
    wx.navigateTo({
      url: "/package/index/pages/bookSearch/bookSearch"
    })
  },


  //获取列表书记

  getTypelist (params) {

    var _this = this
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAdultType/auth',
      method: 'POST',
      data:params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success:(res) => {
        if (res.data.code == 200) {
          wx.hideLoading()
          _this.setData({
            list:res.data.data
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      }
    })
  },

  goNewtype () {
    wx.navigateTo({
      url: '/pages/newindex/newindex',
    })
  },


  getFivepingdao () {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAdultByAgeType',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
      
          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新

          var list = []

          res.data.data.forEach(function (item,index) {
            item.hobbyTypeName = item.hobbyTypeName.split(',').length != [] && item.hobbyTypeName.split(',').length > 2 || item.hobbyTypeName.split(',').length == 2 ? item.hobbyTypeName.split(',')[0] + ',' + item.hobbyTypeName.split(',')[1] : item.hobbyTypeName

            list.push(item)
          })
          _this.setData({
            pindaolist: list
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getWeichengnian() {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAdultType/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          
          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新
          _this.setData({
            pindaolist2: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getChennianren(params){
    var _this = this

    var url = wx.getStorageSync('token') != '' ? 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAdultTypes/auth' :'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAdultTypes'
    wx.request({
      url: url,
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
      

          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新


          _this.setData({
            total: res.data.count
          })


          var list = _this.data.pindaolist3

          res.data.data.forEach(function (item,index) {
            list.push(item)
          })
          _this.setData({
            pindaolist3: list
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (wx.getStorageSync('token') == '') {
      if (options.scene) {
        wx.setStorageSync('scene',options.scene)
      }
      if (options.userIds) {
        wx.setStorageSync('userIds', options.userIds)
      }

    } else {

      if (options.scene) {
        var params = {
          sceneKey: decodeURIComponent(options.scene)
        }
        this.getKey(params)
      }
      if (options.userIds) {
        var params = {
          inviterId: options.userIds
        }
        this.getInvited(params)
      }

      this.getAihao()



     

        if (this.data.getHongbao == false) {
          this.getStatusopen()
          // this.setData({
          //   openNew: true
          // })
        }

      
    }
    this.getAllpindao()
  
    this.getChennianren(this.data.params2)
  },



  getKey(params) {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/scene/values/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          var params = {
            inviterId: res.data.data.userId
          }
          _this.getInvited(params)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },



  getInvited(params) {
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/scene/bindInviter/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          console.log('绑定成功')
          wx.removeStorageSync('scene')
          wx.removeStorageSync('userIds')
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },


  //书本详情
  bookdetail(e) {
    console.log(e)


    // if (wx.getStorageSync('token') == '') {
    //   this.setData({
    //     istokenPop: true
    //   })
    //   return
    // }

    var bookId = e.currentTarget.dataset.bookid
    wx.navigateTo({
      url: '/package/index/pages/bookdetail/bookdetail?bookId=' + bookId,
    })
  },


  getAllpindao() {

    var params = {
      page: 1,
      size: 9999999
    }

    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
  
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findAllAdultByAge',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading()

          wx.hideNavigationBarLoading() //完成停止加载

          wx.stopPullDownRefresh() //停止下拉刷新
          _this.setData({
            total3: res.data.count
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  //查询用户绑定的兴趣爱好

  getAihao() {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/findHobbysByUserId/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          if (res.data.data==""&&res.data.data==null&&res.data.data.length==0) {
            wx.navigateTo({
              url: '/pages/newindex/newindex',
            })
          }
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }
      }
    })
  },


  getIcons ()  {

    var _this = this

  
    var url = wx.getStorageSync('token') != '' ? 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findFixAdultType/auth' :'https://devapi.xiaoshitimebank.com/user/sdx/sdx/FirstPage/hobby/findFixAdultType2'
    wx.request({
      url: url,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          _this.setData({
            icons: res.data.data
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },



  goNewdehuodong () {
    wx.navigateTo({
      url: '/package/index/pages/newHuodong/newHuodong',
    })
  },


  getHongbaoApi () {
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/findWasGetScore/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          _this.setData({
            getHongbao: res.data.data == 0 ? true:false
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

//关闭活动
  closeActivity () {
    // console.log('1111111')
    this.setData({
      getHongbao: false
    })

    if (wx.getStorageSync('token')!='') {
      this.getStatusopen()
    }


  
  },


  getNumapi(encrypted, iv) {



    var _this = this
    var params = {
      encrypted: encrypted,
      sessionKey: wx.getStorageSync('sessionKey'),
      iv: iv
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/bindPhone/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: '获取成功',
            icon: 'none',
            duration: 2000
          })


        _this.setData({
          hasphone: true
        })


        setTimeout(function () {
          _this.getHongbaomy()
        },2000)

    


        } else {
          wx.showToast({
            title: '授权失败,请再次授权',
            icon: 'none'
          })
        }
      }
    })
  },


  getWasphone() {

    var _this = this


      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/wasBindPhone/auth',
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
          "token": wx.getStorageSync('token'),
          "uid": wx.getStorageSync('uuid')
        },
        success: (res) => { 
          if (res.data.code == 200) {
            
            _this.setData({
              hasphone: res.data.data == 1?true: false
            })

          }
        }
      })
},


  getSession(code, encrypted, iv) {
    var params = {
      code: code,
      isSdx: 1
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/checkAuth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.success) {
          wx.removeStorageSync('sessionKey')
          wx.setStorageSync('sessionKey', res.data.data.session_key)
          this.getNumapi(res.data.data.session_key, encrypted, iv)
        }
      }
    })
  },

  getPhoneNumber (e) {

    var that = this
    if (e.detail.errMsg != "getPhoneNumber:ok"){
      wx.showToast({
        title: '请授权您的手机号',
        icon:'none'
      })
    }else{


      wx.checkSession({
        success: function (res) {
          console.log('处于登录状态')

          that.getNumapi(e.detail.encryptedData, e.detail.iv)
        },
        fail: function (res) {
          console.log("需要重新登录")
          wx.login({
            success: function (res) {
              if (res.code) {
                console.log(res.code)


                that.getSession(res.code, e.detail.encryptedData, e.detail.iv)
              }
            }
          })
        }
      })
      // wx.login({
      //   success: function (res) {
      //     if (res.code) {
      //       console.log(res.code)
      //       that.getNumapi(res.code, e.detail.encryptedData, e.detail.iv)
      //     }
      //   }
      // })
    }
  },

  getHongbaomy () {

    var _this = this
    wx.showLoading({
      title: '领取中',
    })
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/addUserScore/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res)=>{
        if (res.data.code == 200) {
          wx.hideLoading()
          wx.showToast({
            title: '领取成功',
            icon: 'none',
            duration: 2000
          })

          _this.setData({
            getHongbao: false
          })
          
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      }
    })
  },


  getDingyue(wasNotice) {

    var _this = this

    var params = {
      wasNotice: wasNotice
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/updateWasNotice/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res)=>{
        if (res.data.code == 200) {
    
          wx.showToast({
            title: wasNotice == 0 ? '取消授权':'授权成功',
            icon:'none'
          })
          _this.setData({ 
            openNew: false
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  getAllshouquans () {

    var _this = this
    wx.requestSubscribeMessage({
      tmplIds: ["LVzud8OH3aHKpkwOBYKcL0pntVnKEGlTOHvUcIlzOXc"],
      success: (res) => {

        console.log(JSON.stringify(res))

        if (res['LVzud8OH3aHKpkwOBYKcL0pntVnKEGlTOHvUcIlzOXc'] === 'accept') {

          

          _this.getDingyue(1)
        


        }else{
          _this.getDingyue(0)
        }

      },
      fail(err) {
        //失败
        console.error(err);
        // reject()
      }
    })
  },


  getStatusopen(){

    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/message/findWasNotice/auth',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res)=>{
        if (res.data.code == 200) {
          _this.setData({
            openNew: res.data.data == 0 ? true: false
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      }
    })
  },


  formatName(name) {
    let newStr;
    if (name.length === 2) {
      newStr = name.substr(0, 1) + '*';
    } else if (name.length > 2) {
      let char = '';
      for (let i = 0, len = name.length - 2; i < len; i++) {
        char += '*';
      }
      newStr = name.substr(0, 1) + char + name.substr(-1, 1);
    } else {
      newStr = name;
    }

    return newStr;
  },


  getDanote () {

    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/global/firstPageDonate',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
      },
      success: (res)=>{
        if (res.data.code == 200) {
          for (var i = 0;i< res.data.data.length;i++) {
            res.data.data[i].donaterName = _this.formatName(res.data.data[i].donaterName)


            res.data.data[i].thuName = _this.formatName(res.data.data[i].thuName)
          
        }
          

          _this.setData({
            danote: res.data.data
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    app.getUserset()
    if (wx.getStorageSync('scene')) {
      var params = {
        sceneKey: decodeURIComponent(wx.getStorageSync('scene'))
      }
      this.getKey(params)
    }
    if (wx.getStorageSync('userIds')) {
      var params = {
        inviterId: wx.getStorageSync('userIds')
      }
      this.getInvited(params)
    }

    // this.getAllshouquans()

    this.getIcons()

    // this.getAllpindao()

    this.getBanner()

    this.getFivepingdao()

    this.getWeichengnian()


    this.getDanote()

    this.getHongbaoApi()



    this.setData({
      token: wx.getStorageSync('token')
    })




    app.watch(this, {
      token: function (newVal, oldVal) {
        // console.log(newVal,oldVal)

    

        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
       

        var page = "params2.page"
        var size = "params2.size"
        this.setData({
          [page]: 1,
          [size]: 2,
          pindaolist3: [],
        })

        this.getChennianren(this.data.params2)


        this.getIcons()
        this.getAllpindao()

        this.getBanner()

        this.getFivepingdao()

        this.getWeichengnian()
      }
    })

    

    // this.getTypelist(this.data.params)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()

    var page = "params2.page"
    var size = "params2.size"
    this.setData({
      [page]: 1,
      [size]: 2,
      pindaolist3: [],
    })

    this.onLoad()

    this.onShow()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pindaolist3.length != this.data.total) {
      this.data.params2.page += 1
      this.getChennianren(this.data.params2)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;

    return {

      title: '原价收书,二折买书',

      path: '/pages/index/index',

      imageUrl: 'https://timebank-prod-img.oss-cn-hangzhou.aliyuncs.com/Slx/1_sytp/syfxt.png',
      success: function (res) {

        console.log("转发成功:" + JSON.stringify(res));

        wx.showToast({
          title: '转发成功',
          icon: 'none'
        })

        // that.shareClick();

      }
    }
  }

})